import cv2
import numpy as np
from PIL import ImageGrab


def empty(x):
    print(x)


img = cv2.imread('./sss.png')
# img = cv2.resize(img, (500, 500))
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

cv2.namedWindow('trackerbar', cv2.WINDOW_AUTOSIZE)
cv2.createTrackbar('hue-min', 'trackerbar', 0, 180, empty)
cv2.createTrackbar('hue-max', 'trackerbar', 180, 180, empty)
cv2.createTrackbar('sat-min', 'trackerbar', 0, 255, empty)
cv2.createTrackbar('sat-max', 'trackerbar', 255, 255, empty)
cv2.createTrackbar('val-min', 'trackerbar', 0, 255, empty)
cv2.createTrackbar('val-max', 'trackerbar', 255, 255, empty)

while True:
    h_min = cv2.getTrackbarPos('hue-min', 'trackerbar')
    h_max = cv2.getTrackbarPos('hue-max', 'trackerbar')
    s_min = cv2.getTrackbarPos('sat-min', 'trackerbar')
    s_max = cv2.getTrackbarPos('sat-max', 'trackerbar')
    v_min = cv2.getTrackbarPos('val-min', 'trackerbar')
    v_max = cv2.getTrackbarPos('val-max', 'trackerbar')

    lower = np.array([h_min, s_min, v_min])
    upper = np.array([h_max, s_max, v_max])
    print(f"最小范围：{lower}\n最大范围：{upper}")
    mask = cv2.inRange(hsv, lower, upper)

    res = cv2.bitwise_and(img, img, mask=mask)
    cv2.imshow('mask', mask)
    cv2.imshow('tracker', res)
    cv2.imshow('img', img)
    cv2.waitKey(1)
